package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import sun.security.krb5.internal.ktab.KeyTabInputStream;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @date 2023/4/15
 */
@Slf4j
@RequestMapping("/setmeal")
@RestController
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value ="setmelCache" ,allEntries = true )
    @PostMapping
    public R<String> addSetmeal(@RequestBody SetmealDto setmealDto) {
        //1.调用service的新增方法
        setmealService.addSetmealWithDish(setmealDto);
        //2.返回结果
        return R.success("新增成功！");
    }

    /**
     * 分页查询
     *
     * @param page     当前页码
     * @param pageSize 每页条数
     * @param name     套餐名称
     * @return
     */
    @GetMapping("/page")
    public R page(@RequestParam(defaultValue = "1") Integer page,
                  @RequestParam(defaultValue = "10") Integer pageSize, String name) {
        //1.调用service的分页查询
        Page<SetmealDto> setmealDtoPage = setmealService.getPage(page, pageSize, name);
        //2.返回结果
        return R.success(setmealDtoPage);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @CacheEvict(value ="setmelCache" ,allEntries = true )
    @DeleteMapping
    public R<String> remove(@RequestParam List<Long> ids) {
        //1.调用service的删除
        setmealService.removeWithDish(ids);
        //2.返回结果
        return R.success("删除成功");
    }

    /**
     * 获取套餐列表
     *
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setmelCache", key = "#setmeal.id+'_'+#setmeal.status")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        //1.创建条件对象，构造查询条件
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        wrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());

        //2.调用service的列表查询方法, 查询setmeal列表信息（根据分类id和状态）,得到List<Setmeal>
        List<Setmeal> list = setmealService.list(wrapper);

        //3.返回结果
        return R.success(list);
    }

    /*
     * 根据id查询套餐信息*/
    @CacheEvict(value ="setmelCache" ,allEntries = true )
    @PutMapping
    public R<String> modify(@RequestBody SetmealDto setmealDto) {
        log.info("修改套餐信息:{}", setmealDto);
//        执行更新
        setmealService.updateWithDish(setmealDto);

        return R.success("修改套餐信息成功");
    }

    //套餐查询回显
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable("id") Long id) {
        Setmeal byId = setmealService.getById(id);
        SetmealDto dishDto = new SetmealDto();
        Long categoryId = byId.getCategoryId();
        Category byId1 = categoryService.getById(categoryId);
        String name = byId1.getName();
        dishDto.setCategoryName(name);
        BeanUtils.copyProperties(byId, dishDto);
        LambdaQueryWrapper<SetmealDish> laq = new LambdaQueryWrapper<>();
        laq.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(laq);

        dishDto.setSetmealDishes(list);
        return R.success(dishDto);
    }

    @CacheEvict(value ="setmelCache" ,allEntries = true )
    @PostMapping("/status/{status}")
    public R<String> updateStatusById(@PathVariable Integer status, @RequestParam Long[] ids) {
// 增加日志验证是否接收到前端参数。
        log.info("根据id修改菜品的状态:{},id为:{}", status, ids);
// 通过id查询数据库。修改id为ids数组中的数据的菜品状态status为前端页面提交的status。
        for (int i = 0; i < ids.length; i++) {
            Long id = ids[i];
//根据id得到每个dish菜品。
            Setmeal dish = setmealService.getById(id);
            dish.setStatus(status);
            setmealService.updateById(dish);
        }
        return R.success("修改菜品状态成功");
    }

}
